// js/ui.js

// 获取 DOM 元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const nextCanvas = document.getElementById('nextPieceCanvas');
const nextCtx = nextCanvas.getContext('2d');
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const startButton = document.getElementById('startButton');
const leaderboardButton = document.getElementById('leaderboardButton');
const statusMessageElement = document.getElementById('statusMessage');

// 弹窗元素
const gameOverModal = document.getElementById('gameOverModal');
const finalScoreElement = document.getElementById('finalScore');
const playerNameInput = document.getElementById('playerNameInput');
const submitScoreButton = document.getElementById('submitScoreButton');
const restartButton = document.getElementById('restartButton');
const submitStatusElement = document.getElementById('submitStatus');

const leaderboardModal = document.getElementById('leaderboardModal');
const leaderboardContentElement = document.getElementById('leaderboardContent');
const closeLeaderboardButton = document.getElementById('closeLeaderboardButton');
const refreshLeaderboardButton = document.getElementById('refreshLeaderboardButton');
const leaderboardStatusElement = document.getElementById('leaderboardStatus');


// 初始化 Canvas 尺寸
function setupCanvases() {
    canvas.width = COLS * BLOCK_SIZE;
    canvas.height = ROWS * BLOCK_SIZE;
    ctx.scale(BLOCK_SIZE, BLOCK_SIZE); // 使用缩放简化绘制坐标

    nextCanvas.width = NEXT_COLS * BLOCK_SIZE;
    nextCanvas.height = NEXT_ROWS * BLOCK_SIZE;
    nextCtx.scale(BLOCK_SIZE, BLOCK_SIZE);
}

// 绘制单个方块
function drawBlock(context, x, y, color) {
    context.fillStyle = color;
    context.fillRect(x, y, 1, 1); // 因为我们缩放了 context，所以这里是 1x1
    context.strokeStyle = '#666'; // 方块边框颜色
    context.lineWidth = 0.05; // 同样受缩放影响
    context.strokeRect(x, y, 1, 1);
}

// 清空 Canvas
function clearCanvas(context, canvasElement) {
    context.fillStyle = '#e0e0e0'; // 背景色
    // 需要使用原始的 canvas 尺寸来清空
    context.save(); // 保存当前变换状态
    context.setTransform(1, 0, 0, 1, 0, 0); // 重置变换
    context.fillRect(0, 0, canvasElement.width, canvasElement.height);
    context.restore(); // 恢复之前的变换（缩放）
}


// 绘制游戏区域 (board)
function drawBoard(board) {
    board.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value > 0) { // value 是颜色索引
                drawBlock(ctx, x, y, COLORS[value]);
            }
        });
    });
}

// 绘制当前活动的方块 (piece)
function drawPiece(piece) {
    piece.shape.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value > 0) {
                drawBlock(ctx, piece.x + x, piece.y + y, COLORS[value]);
            }
        });
    });
}

// 绘制下一个方块预览
function drawNextPiece(piece) {
    clearCanvas(nextCtx, nextCanvas);
    const shape = piece.shape;
    const colorIndex = shape.flat().find(val => val > 0) || 1; // 找到方块的颜色索引
    const color = COLORS[colorIndex];
    // 计算偏移量使方块居中显示在预览区
    const offsetX = (NEXT_COLS - shape[0].length) / 2;
    const offsetY = (NEXT_ROWS - shape.length) / 2;

    shape.forEach((row, y) => {
        row.forEach((value, x) => {
            if (value > 0) {
                drawBlock(nextCtx, offsetX + x, offsetY + y, color);
            }
        });
    });
}

// 更新分数显示
function updateScoreDisplay(score) {
    scoreElement.textContent = score;
}

// 更新等级显示
function updateLevelDisplay(level) {
    levelElement.textContent = level;
}

// 显示游戏结束弹窗
function showGameOverModal(score) {
    finalScoreElement.textContent = score;
    playerNameInput.value = ''; // 清空输入框
    submitStatusElement.textContent = ''; // 清空状态消息
    submitStatusElement.className = 'status-message'; // 重置样式
    submitScoreButton.disabled = false; // 启用提交按钮
    gameOverModal.classList.add('visible');
}

// 隐藏游戏结束弹窗
function hideGameOverModal() {
    gameOverModal.classList.remove('visible');
}

// 显示排行榜弹窗
function showLeaderboardModal(scores) {
    leaderboardContentElement.innerHTML = ''; // 清空旧内容
    leaderboardStatusElement.textContent = '';
    leaderboardStatusElement.className = 'status-message';

    if (!scores || scores.length === 0) {
        leaderboardContentElement.innerHTML = '<p>排行榜为空或加载失败。</p>';
    } else {
        const list = document.createElement('ol');
        scores.forEach((record, index) => {
            const item = document.createElement('li');
            // 简单处理时间戳显示
            const timestamp = record.timestamp ? new Date(record.timestamp).toLocaleString('zh-CN') : 'N/A';
            item.innerHTML = `
                <span class="player-name">${index + 1}. ${record.playerName || '匿名'}</span>
                <span class="player-score">${record.score}</span>
                <br><small style="color: #888;">${timestamp}</small>
            `;
            list.appendChild(item);
        });
        leaderboardContentElement.appendChild(list);
    }
    leaderboardModal.classList.add('visible');
}

// 隐藏排行榜弹窗
function hideLeaderboardModal() {
    leaderboardModal.classList.remove('visible');
}

// 设置状态消息 (用于 API 调用反馈等)
function setStatusMessage(element, message, isError = false) {
    element.textContent = message;
    if (isError) {
        element.className = 'status-message error';
    } else if (message) {
         element.className = 'status-message success';
    } else {
         element.className = 'status-message';
    }
}